<template>
  <div class="events-container">
    <!-- 事件按钮区域 -->
    <div class="events_btn">
      <el-row :gutter="30" justify="space-around">
        <el-col :span="6" v-for="(event, index) in events" :key="index">
          <div class="btn_div">
            <button 
              class="button" 
              :class="{ active: currentEvent === event.name }"
              :data-text="event.name"
              @click="handleEventClick(event.name)"
            >
              <span class="actual-text">{{ event.name }}</span>
              <span aria-hidden="true" class="hover-text">{{ event.name }}</span>
            </button>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 表单区域 -->
    <div class="form-container" v-if="currentEvent">
      <div class="form-header">
        <h2>{{ currentEvent }}表单</h2>
      </div>
      
      <!-- 灌溉事件表单 -->
      <div class="crop-form-container" v-if="currentEvent === '灌溉事件'">
        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">灌溉时间<span class="required">*</span></label>
            </div>
            <input v-model="irrigationForm.irrigationTime" type="datetime-local" class="form-input" />
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">灌溉量<span class="required">*</span></label>
            </div>
            <input v-model="irrigationForm.irrigationVolume" type="number" class="form-input" placeholder="请输入灌溉量" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">计量单位<span class="required">*</span></label>
            </div>
            <select v-model="irrigationForm.volumeUnit" class="form-select">
              <option value="" disabled selected>请选择计量单位</option>
              <option value="立方米">立方米</option>
              <option value="升">升</option>
              <option value="吨">吨</option>
              <option value="公斤">公斤</option>
            </select>
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">灌溉方式<span class="required">*</span></label>
            </div>
            <select v-model="irrigationForm.irrigationMethod" class="form-select">
              <option value="" disabled selected>请选择灌溉方式</option>
              <option value="滴灌">滴灌</option>
              <option value="喷灌">喷灌</option>
              <option value="漫灌">漫灌</option>
              <option value="其他">其他</option>
            </select>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">灌溉面积(亩)<span class="required">*</span></label>
            </div>
            <input v-model="irrigationForm.irrigationArea" type="number" class="form-input" placeholder="请输入灌溉面积" />
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">灌溉前湿度(%)<span class="required">*</span></label>
            </div>
            <input v-model="irrigationForm.humidityBefore" type="number" class="form-input" placeholder="请输入灌溉前湿度" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">灌溉后湿度(%)<span class="required">*</span></label>
            </div>
            <input v-model="irrigationForm.humidityAfter" type="number" class="form-input" placeholder="请输入灌溉后湿度" />
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">操作人<span class="required">*</span></label>
            </div>
            <input v-model="irrigationForm.operator" type="text" class="form-input" placeholder="请输入操作人" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">灌溉图片</label>
            <image-upload v-model="irrigationForm.irrigatImg"  placeholder="请上传灌溉图片" />
          </div>

          <div class="form-item">
            <!-- 空白占位，保持布局一致 -->
          </div>
        </div>

        
      </div>

      <!-- 喷药事件表单 -->
      <div class="crop-form-container" v-if="currentEvent === '喷药事件'">
        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">施药日期<span class="required">*</span></label>
            </div>
            <input v-model="sprayingForm.applicationDate" type="datetime-local" class="form-input" />
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">农药ID<span class="required">*</span></label>
            </div>
            <input v-model="sprayingForm.pesticideId" type="text" class="form-input" placeholder="请输入农药ID" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">施用面积(亩)<span class="required">*</span></label>
            </div>
            <input v-model="sprayingForm.applicationArea" type="number" class="form-input" placeholder="请输入施用面积" />
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">施用方式<span class="required">*</span></label>
            </div>
            <select v-model="sprayingForm.applicationMethod" class="form-select">
              <option value="" disabled selected>请选择施用方式</option>
              <option value="喷雾">喷雾</option>
              <option value="喷粉">喷粉</option>
              <option value="熏蒸">熏蒸</option>
              <option value="其他">其他</option>
            </select>
          </div>
        </div>

        

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">防治效果反馈</label>
            </div>
            <textarea v-model="sprayingForm.efficacyFeedback" class="fixed-textarea" placeholder="请输入防治效果反馈(选填)"></textarea>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">喷药图片</label>
            <image-upload v-model="sprayingForm.sprayImg" placeholder="请上传喷药图片" />
          </div>

          <div class="form-item">
            <!-- 空白占位，保持布局一致 -->
          </div>
        </div>
      </div>

      <!-- 施肥事件表单 -->
      <div class="crop-form-container" v-if="currentEvent === '施肥事件'">
        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">施肥日期<span class="required">*</span></label>
            </div>
            <input v-model="fertilizationForm.fertilizationDate" type="datetime-local" class="form-input" />
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">肥料ID<span class="required">*</span></label>
            </div>
            <input v-model="fertilizationForm.fertilizerId" type="text" class="form-input" placeholder="请输入肥料ID" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">施肥量<span class="required">*</span></label>
            </div>
            <input v-model="fertilizationForm.fertilizationAmount" type="number" class="form-input" placeholder="请输入施肥量" />
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">计量单位<span class="required">*</span></label>
            </div>
            <select v-model="fertilizationForm.amountUnit" class="form-select">
              <option value="" disabled selected>请选择计量单位</option>
              <option value="公斤">公斤</option>
              <option value="吨">吨</option>
              <option value="升">升</option>
              <option value="其他">其他</option>
            </select>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">施肥方式<span class="required">*</span></label>
            </div>
            <select v-model="fertilizationForm.fertilizationMethod" class="form-select">
              <option value="" disabled selected>请选择施肥方式</option>
              <option value="基肥">基肥</option>
              <option value="追肥">追肥</option>
              <option value="叶面肥">叶面肥</option>
              <option value="其他">其他</option>
            </select>
          </div>

          <div class="form-item">
            <!-- 空白占位，保持布局一致 -->
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">施肥图片</label>
            <image-upload v-model="fertilizationForm.fertImg" placeholder="请上传施肥图片" />
          </div>

          <div class="form-item">
            <!-- 空白占位，保持布局一致 -->
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">备注信息</label>
            <textarea v-model="fertilizationForm.remark" class="fixed-textarea" placeholder="请输入备注信息(选填)"></textarea>
          </div>
        </div>
      </div>

      <!-- 其他事件表单 -->
      <div class="crop-form-container" v-if="currentEvent === '其他事件'">
        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">事件主题<span class="required">*</span></label>
            </div>
            <input v-model="otherEventForm.eventSubject" type="text" class="form-input" placeholder="请输入事件主题" />
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">事件发生日期<span class="required">*</span></label>
            </div>
            <input v-model="otherEventForm.eventOccurrenceDate" type="datetime-local" class="form-input" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">事件概述<span class="required">*</span></label>
            </div>
            <textarea v-model="otherEventForm.eventOverview" class="fixed-textarea" placeholder="请输入事件概述"></textarea>
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">事件详情</label>
            </div>
            <textarea v-model="otherEventForm.eventDetails" class="fixed-textarea" placeholder="请输入事件详情(选填)"></textarea>
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">事件影响</label>
            </div>
            <textarea v-model="otherEventForm.eventImpact" class="fixed-textarea" placeholder="请输入事件影响(选填)"></textarea>
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">事件处理人</label>
            </div>
            <input v-model="otherEventForm.eventHandler" type="text" class="form-input" placeholder="请输入事件处理人" />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <div>
              <label class="form-label">处理措施</label>
            </div>
            <textarea v-model="otherEventForm.processingMeasures" class="fixed-textarea" placeholder="请输入处理措施(选填)"></textarea>
          </div>

          <div class="form-item">
            <div>
              <label class="form-label">关联文件</label>
            </div>
            <FileUpload 
              v-model="relatedFilesArray" 
              :limit="5" 
              :file-size="10"
              :file-type="['doc', 'docx', 'xls', 'xlsx', 'pdf', 'jpg', 'jpeg', 'png', 'txt']"
            />
          </div>
        </div>

        <div class="form-row">
          <div class="form-item">
            <label class="form-label">备注信息</label>
            <textarea v-model="otherEventForm.remark" class="fixed-textarea" placeholder="请输入备注信息(选填)"></textarea>
          </div>
        </div>
      </div>

      <!-- 提交按钮 -->
      <div class="form-footer">
        <el-button @click="resetForm" type="default">重置</el-button>
        <el-button @click="submitForm" style="background-color: #2e7d32; border-color: #2e7d32;" type="primary">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
// 灌溉
import {addIrrgatcrop} from '@/api/ncpsy/management/irrgatcrop.js'
// 施肥
import {addFertcrop} from '@/api/ncpsy/management/fertcrop.js'
//喷药
import {addPestCrop} from '@/api/ncpsy/management/pestcrop.js'
//其他
import {addOtherEvent} from '@/api/ncpsy/management/otherEvent.js'
import { ref, reactive, computed } from 'vue'
import { useRoute } from 'vue-router';
import useUserStore from '@/store/modules/user'
import { ElMessage } from 'element-plus'
const route = useRoute();
const cropEventId = route.query.cropEventId;
const userStore = useUserStore();
const userId = userStore.id;
// 定义事件数据
const events = ref([
  { name: '灌溉事件' },
  { name: '喷药事件' },
  { name: '施肥事件' },
  { name: '其他事件' }
])

// 当前选中的事件
const currentEvent = ref('')

// 灌溉事件表单数据
const irrigationForm = reactive({
  cropEventId: cropEventId,
  irrigationTime: '',
  irrigationVolume: '',
  volumeUnit: '',
  irrigatImg: '',
  irrigationMethod: '',
  irrigationArea: '',
  humidityBefore: '',
  humidityAfter: '',
  operator: '',
  userId: userId
})

// 喷药事件表单数据
const sprayingForm = reactive({
cropEventId: cropEventId,
  applicationDate: '',
  pesticideId: '',
  applicationArea: '',
  applicationMethod: '',
  usageAmount: '',
  safeInterval: '',
  efficacyFeedback: '',
  sprayImg: '',
  status:'有效',
  userId: userId
})

// 施肥事件表单数据
const fertilizationForm = reactive({
  cropEventId: cropEventId,
  userId: userId,
  fertilizationDate: '',
  fertilizerId: '',
  fertilizationAmount: '',
  amountUnit: '',
  fertilizationMethod: '',
  fertImg: '',
  remark: '',
  status:'有效'
})

// 其他事件表单数据
const otherEventForm = reactive({
  cropEventId: cropEventId,
  eventSubject: '',
  eventOverview: '',
  eventDetails: '',
  eventImpact: '',
  eventHandler: '',
  eventOccurrenceDate: '',
  processingMeasures: '',
  relatedFiles: '',
  remark: '',
  status: '有效',
  userId: userId
})

// 处理文件上传的计算属性
const relatedFilesArray = computed({
  get() {
    // 将字符串转换为数组格式
    if (!otherEventForm.relatedFiles) return [];
    return otherEventForm.relatedFiles.split(',').filter(url => url.trim()).map(url => ({
      name: url.split('/').pop() || url,
      url: url
    }));
  },
  set(value) {
    // 将数组转换为字符串格式
    if (Array.isArray(value)) {
      const fileUrls = value.map(file => file.url || file.name).filter(url => url);
      otherEventForm.relatedFiles = fileUrls.join(',');
    } else {
      otherEventForm.relatedFiles = '';
    }
  }
})

// 处理事件按钮点击
const handleEventClick = (eventName) => {
  currentEvent.value = eventName
  switch(eventName) {
    case '灌溉事件':
      handleIrrigation();
      break;
    case '喷药事件':
      handleSpraying();
      break;
    case '施肥事件':
      handleFertilization();
      break;
    case '其他事件':
      handleOtherEvent();
      break;
    default:
      console.log('未知事件类型');
  }
}

// 灌溉事件处理
const handleIrrigation = () => {
  // 这里应该处理灌溉事件的逻辑，而不是直接调用API
  console.log('处理灌溉事件');
}

// 喷药事件处理
const handleSpraying = () => {
  // 这里应该处理喷药事件的逻辑，而不是直接调用API
  console.log('处理喷药事件');
}

// 施肥事件处理
const handleFertilization = () => {
  // 这里应该处理施肥事件的逻辑，而不是直接调用API
  console.log('处理施肥事件');
}

// 格式化日期时间为本地字符串
const formatDateTimeLocal = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  // 将日期转换为datetime-local格式 (YYYY-MM-DDTHH:MM)
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}`;
}

// 其他事件处理
const handleOtherEvent = () => {
  // 这里应该处理其他事件的逻辑，而不是直接调用API
  console.log('处理其他事件');
}

// 重置表单
const resetForm = () => {
  switch(currentEvent.value) {
    case '灌溉事件':
      Object.assign(irrigationForm, {
        irrigationTime: '',
        irrigationVolume: '',
        volumeUnit: '',
        irrigatImg: '',
        irrigationMethod: '',
        irrigationArea: '',
        humidityBefore: '',
        humidityAfter: '',
        operator: '',
        remark: ''
      })
      break;
    case '喷药事件':
      Object.assign(sprayingForm, {
        applicationDate: '',
        pesticideId: '',
        applicationArea: '',
        applicationMethod: '',
        usageAmount: '',
        safeInterval: '',
        efficacyFeedback: '',
        sprayImg: ''
      })
      break;
    case '施肥事件':
          Object.assign(fertilizationForm, {
            fertilizationDate: '',
            fertilizerId: '',
            fertilizationAmount: '',
            amountUnit: '',
            fertilizationMethod: '',
            fertImg: '',
            remark: ''
          })
          break;
    case '其他事件':
      Object.assign(otherEventForm, {
        eventSubject: '',
        eventOverview: '',
        eventDetails: '',
        eventImpact: '',
        eventHandler: '',
        eventOccurrenceDate: '',
        processingMeasures: '',
        relatedFiles: '',
        remark: ''
      })
      break;
    default:
      ElMessage.warning('请选择一个事件类型');
  }
  ElMessage.success('表单已重置');
}

// 提交表单
const submitForm = () => {
  switch(currentEvent.value) {
    case '灌溉事件':
      console.log('提交灌溉事件表单', irrigationForm);
      // 调用API提交灌溉数据
      addIrrgatcrop(irrigationForm)
        .then(response => {
          console.log('灌溉事件提交成功', response);
          ElMessage.success('灌溉事件表单提交成功！');
          window.location.reload();
        })
        .catch(error => {
          console.error('灌溉事件提交失败', error);
          ElMessage.error('灌溉事件表单提交失败！');
        });
      break;
    case '喷药事件':
      console.log('提交喷药事件表单', sprayingForm);
      // 调用API提交喷药数据
      addPestCrop(sprayingForm)
        .then(response => {
          console.log('喷药事件提交成功', response);
          ElMessage.success('喷药事件表单提交成功！');
        })
        .catch(error => {
          console.error('喷药事件提交失败', error);
          ElMessage.error('喷药事件表单提交失败！');
        });
      break;
    case '施肥事件':
      console.log('提交施肥事件表单', fertilizationForm);
      // 调用API提交施肥数据
      addFertcrop(fertilizationForm)
        .then(response => {
          console.log('施肥事件提交成功', response);
          ElMessage.success('施肥事件表单提交成功！');
          window.location.reload();
        })
        .catch(error => {
          console.error('施肥事件提交失败', error);
          ElMessage.error('施肥事件表单提交失败！');
        });
      break;
    case '其他事件':
      console.log('提交其他事件表单', otherEventForm);
      // 调用API提交其他事件数据
      addOtherEvent(otherEventForm)
        .then(response => {
          console.log('其他事件提交成功', response);
          ElMessage.success('其他事件表单提交成功！');
        })
        .catch(error => {
          console.error('其他事件提交失败', error);
          ElMessage.error('其他事件表单提交失败！');
        });
      break;
    default:
      ElMessage.warning('请选择一个事件类型');
  }
}
</script>

<style scoped>
.events-container {
  width: 100%;
}

.events_btn {
  padding: 30px;
  margin: 5px 0;
  background-color: #fff;
  border-radius: 10px;
}

.btn_div {
  text-align: center;
}

.button {
  margin: 0;
  background: transparent;
  padding: 0px 16px;
  border: none;
  cursor: pointer;
  height: auto;
}

/* button styling */
.button {
  --border-right: 6px;
  --text-stroke-color: #6a717f;
  --animation-color: #2e7d32;
  --fs-size: 1.2em;
  letter-spacing: 3px;
  text-decoration: none;
  font-size: var(--fs-size);
  font-family: "Arial";
  position: relative;
  color: #6a717f;
  background: transparent;
  padding: 0px 16px;
  border: none;
  cursor: pointer;
  height: auto;
}

/* 实际文本样式 - 添加过渡效果 */
.actual-text {
  transition: opacity 0.5s ease;
}

/* 鼠标悬停时实际文本变为透明 */
.button:hover .actual-text {
  opacity: 0;
}

/* 悬停文本样式 */
.hover-text {
  position: absolute;
  box-sizing: border-box;
  content: attr(data-text);
  color: var(--animation-color);
  width: 0%;
  inset: 0;
  border-right: var(--border-right) solid var(--animation-color);
  overflow: hidden;
  transition: 0.5s;
  -webkit-text-stroke: 1px var(--animation-color);
}

/* 悬停效果 */
.button:hover .hover-text {
  width: 100%;
  filter: drop-shadow(0 0 23px var(--animation-color))
}

/* 点击后保持的样式 */
.button.active .actual-text {
  opacity: 0;
}

.button.active .hover-text {
  width: 100%;
  filter: drop-shadow(0 0 23px var(--animation-color))
}

/* 表单样式 */
.form-container {
  margin: 20px auto;
  padding: 20px;
  border-radius: 20px;
  background-color: #fff;
  box-shadow: rgba(209, 209, 209, 0.438) 5px 5px 10px;
}

.form-header {
  text-align: center;
  margin-bottom: 20px;
}

.form-header h2 {
  color: #2e7d32;
  margin: 0;
}

.crop-form-container {
  margin: 20px auto;
  padding: 20px;
  border-radius: 20px;
  background-color: #fff;
}

.form-row {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.form-item {
  flex: 1 1 calc(50% - 10px);
  min-width: 250px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: start;
}

.form-label {
  font-size: 16px;
  display: inline-block;
  text-align: left;
  margin-bottom: 5px;
}

.required {
  color: #f13939;
}

.form-input,
.form-select {
  font-size: 16px;
  outline: none;
  color: #000;
  background-color: #ffffff;
  border: 2px solid #909399;
  border-radius: 10px;
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
}

.form-select {
  height: 45px;
}

.fixed-textarea {
  width: 100%;
  height: 100px;
  resize: none;
  padding: 10px;
  font-size: 16px;
  border: 2px solid #909399;
  border-radius: 10px;
  box-sizing: border-box;
  outline: none;
  color: #000;
  background-color: #fff;
  font-family: Arial, sans-serif;
}

.form-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
  padding: 0 20px;
}

.form-footer .el-button {
  padding: 12px 30px;
  font-size: 16px;
}

/* FileUpload组件样式调整 */
.upload-file {
  width: 100%;
}

.upload-file .el-upload {
  width: 100%;
}

.upload-file .el-upload .el-button {
  width: 100%;
  background-color: #f5f7fa;
  border: 2px solid #909399;
  border-radius: 10px;
  color: #606266;
  font-size: 16px;
  padding: 10px;
}

.upload-file .el-upload .el-button:hover {
  background-color: #e9e9eb;
  border-color: #909399;
}

.upload-file .el-upload__tip {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.upload-file-list {
  margin-top: 10px;
}

.upload-file-list .el-upload-list__item {
  border-radius: 8px;
  margin-bottom: 8px;
  padding: 8px 12px;
  background-color: #f5f7fa;
}

.upload-file-list .ele-upload-list__item-content-action .el-link {
  font-size: 14px;
}
</style>
